#include <QSqlQuery>
#include "vaccountdatabase.h"
#include "vdatabase.h"

VAccountDataBase::VAccountDataBase()
	:m_accountDatabase(VDataBase::AccountDatabase())
{	
	QSqlQuery(m_accountDatabase).exec("CREATE TABLE IF NOT EXISTS USERS("
		"ACCOUNT TEXT NOT NULL PRIMARY KEY,"
		"PASSWORD TEXT NOT NULL);"
	);//用户表
}

VAccountDataBase* VAccountDataBase::instance()
{
	static VAccountDataBase Instance;
	return &Instance;
}

VAccountDataBase::~VAccountDataBase()
{
}

VUsers VAccountDataBase::registAccount(const QString& account, const QString& password)
{
	QSqlQuery query(m_accountDatabase);
	query.exec(QString("SELECT ACCOUNT FROM USERS WHERE ACCOUNT='%1';")
		.arg(account)); //查询账户是否已经存在
	if (query.next())return VUsers("-1", "-1");

	query.exec(QString("INSERT INTO USERS (ACCOUNT,PASSWORD) VALUES ('%1','%2');")
		.arg(account).arg(password)); //在表中插入记录

	QSqlQuery(VDataBase::ContactDatabase()).exec(QString("CREATE TABLE IF NOT EXISTS '%1' ("
		"FRIEND_ACCOUNT TEXT NOT NULL PRIMARY KEY)"
	).arg(account + "_FRIEND"));//创建联系人表

	return VUsers(account, password);
}

VUsers VAccountDataBase::verifyAccount(const QString& account, const QString& password)
{
	QSqlQuery query(m_accountDatabase);
	query.exec(QString("SELECT * FROM USERS WHERE ACCOUNT='%1'AND PASSWORD='%2';")
		.arg(account).arg(password)); //查询账户
	return query.next() ? VUsers(account, password) : VUsers("-1", "-1");
}

void VAccountDataBase::changePassword(const QString& account, const QString& newPassword)
{
	QSqlQuery query(m_accountDatabase);
	query.exec(QString("SELECT * FROM USERS WHERE ACCOUNT='%1';")
		.arg(account)); //查询账户

	if (query.next())
	{
		query.exec(QString("UPDATE USERS SET PASSWORD ='%1'WHERE ACCOUNT='%2';")
			.arg(newPassword).arg(account)); //修改密码
	}
}